﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Dynamic;
using System.Web.Mvc;
using SDT.Model;
using SDT.Lib.Common;
using SDT.Admin.Properties;
using SDT.Admin.ViewModels;
using SDT.Lib.Paging;
using System.Web.UI.WebControls;
using System.IO;
using System.Threading;
using System.Globalization;
using SDT.Lib.Helpers;

namespace SDT.Admin.Controllers
{
    /// <summary>
    /// Author: Takamaru Nguyen
    /// Date: 24/06/2011
    /// </summary>
    [RoleHelper(Roles = RoleSystem.Question)]
    public class QuestionController : Controller
    {
        private int _pageSize = 10;
        public QuestionController()
        {
            var currentCulture = Thread.CurrentThread.CurrentCulture;
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR");
        }

        SDTDataContext eDataContext = new SDTDataContext();
        //
        // GET: /Question/

        public ActionResult Index(int? page)
        {
            try
            {
                    if (!page.HasValue)
                        page = 1;
                    string order = UserState.getUserStateFromRequest("question.order", "order", "ID").ToString();
                    string orderDir = UserState.getUserStateFromRequest("question.orderDir", "orderDir", "desc").ToString();
                    int catID = Convert.ToInt32(UserState.getUserStateFromRequest("question.CatID", "CatID", 0));
                    string strPub = UserState.getUserStateFromRequest("question.CurrentPubStatus", "CurrentPubStatus", "").ToString();
                    string keyword = UserState.getUserStateFromRequest("question.Keyword", "Keyword", "").ToString();
                    int pageSize = int.Parse(UserState.getUserStateFromRequest("question.pageSize", "PageSize", 20).ToString());
                    
                    int? currentPub = null;
                    if (!string.IsNullOrEmpty(strPub))
                        currentPub = Convert.ToInt32(strPub);

                    IPagedList<Question> quest = eDataContext.Questions
                        .Where(q => (catID > 0 ? q.CatID == catID : true))
                        .Where(q => currentPub.HasValue ? q.PubYN == (currentPub.HasValue && currentPub.Value == 1 ? true : false) : true)
                        .Where(q => (string.IsNullOrEmpty(keyword) ? true :
                            (q.Title.ToLower().Contains(keyword.ToLower().Trim()) ||
                            q.Title.ToLower().Contains(keyword.ToLower().Trim()) ||
                            q.Title.ToLower().Contains(keyword.ToLower().Trim())
                        )))
                        .OrderBy(string.Format("{0} {1}", order, orderDir))
                        .ToPagedList(page.Value - 1, pageSize);

                    List<TreeNodeItem> listTree = eDataContext.QuestionCategories
                                                    .Where(c => c.ActiveYN == true)
                                                    .Select(c => new TreeNodeItem()
                                                    {
                                                        Value = c.ID,
                                                        Text = c.Name,
                                                        ParentID = c.ParentID
                                                    }).ToList();
                    TreeNodeCollection categories = catID > 0 ? new BuiltTreeCollection().BuiltTreeNodeCollection(listTree, catID) : new BuiltTreeCollection().BuiltTreeNodeCollection(listTree);

                    ViewData["orderDir"] = orderDir;
                    ViewData["order"] = order;

                    return View(new QuestionViewModels
                    {
                        Questions = quest,
                        Categories = categories,
                        CurrentCat = catID,
                        CurrentPubStatus = currentPub,
                        Keyword = keyword,
                        ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Question/Details/5

        public ActionResult Details(int id ,int? page)
        {
            try
            {
					if (!page.HasValue ||page <=0) page = 1;
                    if(!string.IsNullOrEmpty(Request["page"]))
                        page = int.Parse(Request["page"]);
                    Question ques = eDataContext.Questions.Where(q => q.ID == id).FirstOrDefault();
                    List<TreeNodeItem> listTree = eDataContext.QuestionCategories
                                                    .Where(c => c.ActiveYN == true)
                                                    .Select(c => new TreeNodeItem()
                                                    {
                                                        Value = c.ID,
                                                        Text = c.Name,
                                                        ParentID = c.ParentID
                                                    }).ToList();
                    TreeNodeCollection categories = ques.CatID.HasValue && ques.CatID.Value > 0 ?
                                            new BuiltTreeCollection().BuiltTreeNodeCollection(listTree, ques.CatID.Value) :
                                            new BuiltTreeCollection().BuiltTreeNodeCollection(listTree);
                    IPagedList<Answer> listA = eDataContext.Answers.Where(a => a.QuestionID == id).ToPagedList(page.Value - 1, _pageSize);
                    
                    return View(new QuestionInputModels
                    {
                        Categories = categories,
                        Question = ques,
                        ListAnswer = listA
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Question/Answer/5

        public ActionResult Answer(int id)
        {
            try
            {
                    int page = 1;
                    if (!string.IsNullOrEmpty(Request["page"]))
                        page = int.Parse(Request["page"]);

                    Question ques = eDataContext.Questions.Where(q => q.ID == id).FirstOrDefault();
                    List<TreeNodeItem> listTree = eDataContext.QuestionCategories
                                                    .Where(c => c.ActiveYN == true)
                                                    .Select(c => new TreeNodeItem()
                                                    {
                                                        Value = c.ID,
                                                        Text = c.Name,
                                                        ParentID = c.ParentID
                                                    }).ToList();
                    TreeNodeCollection categories = ques.CatID.HasValue && ques.CatID.Value > 0 ?
                                            new BuiltTreeCollection().BuiltTreeNodeCollection(listTree, ques.CatID.Value) :
                                            new BuiltTreeCollection().BuiltTreeNodeCollection(listTree);
                    IPagedList<Answer> listA = eDataContext.Answers.Where(a => a.QuestionID == id).ToPagedList(page - 1, _pageSize);

                    return View(new QuestionInputModels
                    {
                        Categories = categories,
                        Question = ques,
                        ListAnswer = listA
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }


        //
        // GET: /Question/Answer/5

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Answer(int id, QuestionInputModels m)
        {
            try
            {
                    UpdateModel(m.Answer);
                    m.Answer.AddBy = UserManager.GetUserId();
                    m.Answer.QuestionID = id;
                    m.Answer.AddDate = DateTime.Now;
                    m.Answer.nViews = 0;
                    if (m.Answer.CheckYN.HasValue && m.Answer.CheckYN.Value)
                    {
                        m.Answer.CheckDate = DateTime.Now;
                        m.Answer.CheckBy = UserManager.GetUserId();
                    }
                    Question q = eDataContext.Questions.Where(qe => qe.ID == id).FirstOrDefault();
                    q.nAnswers = q.nAnswers + 1;

                    eDataContext.Answers.InsertOnSubmit(m.Answer);
                    eDataContext.SubmitChanges();

                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Question/Create

        public ActionResult Create()
        {
            try
            {
                    List<TreeNodeItem> listTree = eDataContext.QuestionCategories
                                                    .Where(c => c.ActiveYN == true)
                                                    .Select(c => new TreeNodeItem()
                                                    {
                                                        Value = c.ID,
                                                        Text = c.Name,
                                                        ParentID = c.ParentID
                                                    }).ToList();
                    TreeNodeCollection categories = new BuiltTreeCollection().BuiltTreeNodeCollection(listTree);
                    
                    return View(new QuestionInputModels
                    {
                        Categories = categories
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        } 

        //
        // POST: /Question/Create

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(QuestionInputModels m)
        {
            try
            {
                    UpdateModel(m.Question);
                    m.Question.AddBy = UserManager.GetUserId();
                    m.Question.CatID = int.Parse(Request["CatID"]);

                    if (m.Question.CheckYN)
                    {
                        m.Question.CheckDate = DateTime.Now;
                        m.Question.CheckBy = UserManager.GetUserId();
                    }
                    eDataContext.Questions.InsertOnSubmit(m.Question);
                    eDataContext.SubmitChanges();

                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Question/Edit/5
 
        public ActionResult Edit(int id)
        {
            try
            {
                    Question ques = eDataContext.Questions.Where(q => q.ID == id).FirstOrDefault();
                    List<TreeNodeItem> listTree = eDataContext.QuestionCategories
                                                    .Where(c => c.ActiveYN == true)
                                                    .Select(c => new TreeNodeItem()
                                                    {
                                                        Value = c.ID,
                                                        Text = c.Name,
                                                        ParentID = c.ParentID
                                                    }).ToList();
                    TreeNodeCollection categories = ques.CatID.HasValue && ques.CatID.Value > 0 ?
                                            new BuiltTreeCollection().BuiltTreeNodeCollection(listTree, ques.CatID.Value) :
                                            new BuiltTreeCollection().BuiltTreeNodeCollection(listTree);
                    
                    return View(new QuestionInputModels
                    {
                        Categories = categories,
                        Question = ques
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /Question/Edit/5

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(int id, QuestionInputModels m)
        {
            try
            {
                    m.Question = eDataContext.Questions.Where(q => q.ID == id).FirstOrDefault();

                    if (!m.Question.CheckYN && bool.Parse(Request["CheckYN"]))
                    {
                        m.Question.CheckDate = DateTime.Now;
                        m.Question.CheckBy = UserManager.GetUserId();
                    }
                    UpdateModel(m.Question);
                    m.Question.ModifyBy = UserManager.GetUserId();
                    m.Question.ModifyDate = DateTime.Now;
                    m.Question.CatID = int.Parse(Request["CatID"]);

                    eDataContext.SubmitChanges();

                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Article/Delete/5
        [Authorize()]
        public ActionResult Delete(int id)
        {
            try
            {
                    int nItem = eDataContext.Answers.Where(d => d.QuestionID == id).Count();
                    if (nItem > 0)
                        throw new Exception("Bạn phải xoá câu trả lời trước khi xoá câu hỏi.");

                    Question formDoc = eDataContext.Questions.Where(f => f.ID == id).FirstOrDefault();

                    return View(formDoc);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /Article/Delete/5

        [HttpPost]
        [Authorize()]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                    Question formDoc = eDataContext.Questions.Where(f => f.ID == id).FirstOrDefault();
                    if (formDoc != null)
                    {
                        eDataContext.Questions.DeleteOnSubmit(formDoc);
                        eDataContext.SubmitChanges();
                    }
                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

		public ActionResult DeleteAnswer(int id, int page)
		{
			try
			{
					if (id < 0) throw new NotSupportedException();
					var CurrentAnswer = eDataContext.Answers.Where(an => an.ID == id).SingleOrDefault();
					var CurrentQuestionID = CurrentAnswer.QuestionID;
					if (CurrentAnswer != null)
					{
						eDataContext.Answers.DeleteOnSubmit(CurrentAnswer);
						eDataContext.SubmitChanges();
						var CurrentQuestion = eDataContext.Questions.Where(q => q.ID == CurrentQuestionID).SingleOrDefault();
						CurrentQuestion.nAnswers = CurrentQuestion.nAnswers - 1;
						CurrentQuestion.nPubAnswers = CurrentQuestion.nPubAnswers - 1;
						eDataContext.SubmitChanges();
						return RedirectToAction("Details", new { id = CurrentQuestionID, page = page });
					}
					else
					{
						return RedirectToAction("Details", new { id = CurrentQuestionID, page = page });
					}
			}
			catch (Exception exp)
			{
				ViewData[Messages.MessageInfo] = exp.Message;
				return View();
			}
		}

		[HttpGet]
		public ActionResult EditAnswer(int id,int page)
		{
			try
			{
				if (page < 0) throw new NotSupportedException();
				if (id < 0) throw new NotSupportedException();
				var AnswerCurrent = eDataContext.Answers.Where(an => an.ID == id).SingleOrDefault();
				if (AnswerCurrent != null)
				{
					var CurrentQuestion = eDataContext.Questions.Where(q => q.ID == AnswerCurrent.QuestionID).SingleOrDefault();
					return View(new AnswerEditModels
														{CurrentQuetion = CurrentQuestion,
														 CurentAnswer = AnswerCurrent,
														 CurrentAnswerID =id,
														 CurentPage =page});
				}
				else
				{

					ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
					return View();
				}
			}
			catch (Exception ex)
			{
				ViewData[Messages.MessageInfo] = ex.Message;
				return View();
			}
		}

		[ValidateInput(false)]
		[HttpPost]
		public ActionResult EditAnswer(AnswerEditModels frm)
		{
			try
			{
				var AnsertCurrent = eDataContext.Answers.Where(an => an.ID == frm.CurrentAnswerID).SingleOrDefault();
				var PubYN = bool.Parse(Request["PubYN"]);
				var CheckYN = bool.Parse(Request["CheckYN"]);
				AnsertCurrent.PubYN = PubYN;
				AnsertCurrent.CheckYN = CheckYN;
				AnsertCurrent.ModifyBy = UserManager.GetUserId();
				AnsertCurrent.ModifyDate = DateTime.Now;
				AnsertCurrent.Answers = frm.CurentAnswer.Answers;
				eDataContext.SubmitChanges();
				return RedirectToAction("Details", new { @id = AnsertCurrent.QuestionID, @page = frm.CurentPage });
			}
			catch (Exception ex)
			{
				ViewData[Messages.MessageInfo] = ex.Message;
				return View();
			}
		}
    }
}
